using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Web.Script.Services;
using System.Linq;
using LogosoftSharepoint.Data_Sources;
using System.Security.Cryptography;
using System.Text;

namespace LogosoftSharepoint.WebServices
{

    public class LoggedInResposne
    {
        public bool IsLoggedIn { get; set; }
        public string Name { get; set; }

        public LoggedInResposne()
        {
            IsLoggedIn = false;
            Name = "";
        }  
    }

    /// <summary>
    /// Summary description for LoginService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class LoginService : System.Web.Services.WebService
    {

        [WebMethod(EnableSession = true)]
        public bool Login(string login, string pass)
        {

            string passHashCoded = GetMD5Hash(pass);

            SharepointSystemDataContext ssdc = new SharepointSystemDataContext();
            var users = from u
                        in ssdc.ls_pracownicy
                        where u.login == login && u.pass == passHashCoded
                        select u;

            if (users.Count() > 0)
            {
                ls_pracownicy user = users.First();
                Session["loggedin"] = user.imie;
                return true;
            }
            else
            {
                if (Session != null)
                {
                    Session.Abandon();
                }
                return false;
            }

        }

        [WebMethod(EnableSession = true)]
        public void Logout()
        {
            Session.Abandon();
        }

        [WebMethod(EnableSession = true)]
        public LoggedInResposne CheckIfLoggedIn()
        {
            LoggedInResposne lr = new LoggedInResposne();
            if (Session["loggedin"] == null)
            {
                lr.IsLoggedIn = false;
            }
            else
            {
                lr.IsLoggedIn = true;
                lr.Name = Session["loggedin"].ToString();
            }
            return lr;
        }

        private string GetMD5Hash(string toBeHashCoded){
            Byte[] originalBytes;
            Byte[] encodedBytes;
           
            MD5 md5 = new MD5CryptoServiceProvider();
            originalBytes = ASCIIEncoding.Default.GetBytes(toBeHashCoded);
            encodedBytes = md5.ComputeHash(originalBytes);

            return BitConverter.ToString(encodedBytes);
        }
    }
}
